<template>
    <div id="batch-upload">
        <div>
            <el-upload
                action
                class="upload-demo"
                drag
                accept=".xlsx, .xls"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handle">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text"><em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传.xlsx, .xls</div>
            </el-upload>
        </div>
    </div>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
export default {
    name: 'batch-upload',
    data () {
        return {
            userBatchList: []
        }
    },
    methods: {
        readFile (file) {//文件读取
            return new Promise(resolve => {
                let reader = new FileReader()
                reader.readAsBinaryString(file)//以二进制的方式读取
                reader.onload = ev => {
                    resolve(ev.target.result)
                }
            })
        },
        async handle (ev) {
            let file = ev.raw
            // console.log(file)
            if (!file) {
                console.log("文件打开失败")
                return
            } else {
                let data = await this.readFile(file)
                let workbook = XLSX.read(data, { type: "binary" })//解析二进制格式数据

                let worksheet = workbook.Sheets[workbook.SheetNames[0]]//获取第一个Sheet
                let result = XLSX.utils.sheet_to_json(worksheet)//json数据格式
                this.userBatchList = result
                // console.log(this.userBatchList)
                this.$emit('batchList', this.userBatchList)
            }
        }
    }
}
</script>

<style>
</style>